<?php

/**
 * This is the model class for table "yii_users".
 *
 * The followings are the available columns in table 'yii_users':
 * @property integer $id
 * @property string $path_to_avatar
 * @property string $full_name
 * @property string $email
 * @property string $password
 * @property string $phone
 * @property integer $type
 */
class User extends CActiveRecord
{
    const ADMIN = 0;
    const CUSTOMER = 1;
    const CLIENT = 2;

    const IMAGES_LOCATION = '/avatars';
    const TEMP_FILE_NAME = '/temp';
    const DEFAULT_AVATAR = '/no_photo.png';

    public $accepted_image_types = array('jpg', 'gif', 'png');

    public $avatar;

    public $verification_code;

    public $password_repeat;

    public $old_user;

	/**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'yii_users';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('full_name, email, password, type, username', 'required'),
            array('password_repeat', 'safe'),
            array('email, username', 'unique'),
            array('email', 'email'),
			array('type', 'numerical', 'integerOnly'=>true),
			array('full_name, password', 'length', 'max'=>256),
			array('email, username', 'length', 'max'=>50),
			array('phone', 'length', 'max'=>20),
			array('path_to_avatar', 'safe'),
            array('verification_code', 'captcha', 'allowEmpty'=>!Yii::app()->user->isGuest),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, path_to_avatar, full_name, email, password, phone, type', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'path_to_avatar' => 'Уже существующее фото',
			'full_name' => 'Полное имя',
			'email' => 'e-mail',
			'password' => 'Пароль',
            'password_repeat' => 'Повтор пароля',
            'avatar' => 'Фото',
            'verification_code' => 'Код проверки',
			'phone' => 'Контактный телефон',
			'type' => 'Тип',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('path_to_avatar',$this->path_to_avatar,true);
		$criteria->compare('full_name',$this->full_name,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('type',$this->type);
        $criteria->compare('username',$this->username,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

    /**
     * Retrieves a label for the current client type
     * @return string a label
     */
    public function getVerboseType(){
        if($this->type == $this::CUSTOMER){
            return "Сотрудник";
        }else if($this->type == $this::ADMIN){
            return "Администратор";
        }
        return "Клиент";
    }

    
    /**
     * loads "old" user object, in future this piece of code
     * must be refactored, using "afterFind" are right
     * @return bool
     */
    public function beforeValidate(){
        $this->old_user = User::model()->findByPk($this->id);
        return true;
    }
    /**
     * Encrypts password field
     * @return boolean
     */
    public function afterValidate(){
            parent::afterValidate();

            $this->avatar = CUploadedFile::getInstance($this,'avatar');

            if($this->avatar != null){

                $avatar_validation_rule = array('avatar', 'file', 'types'=>'jpg, gif, png', 'on'=>'insert, update');
                if(!$this->customValidation($avatar_validation_rule)) return false;
                
                $this->appendWithThumb();
            }

            if(!$this->path_to_avatar){
                $this->appendWithThumb(true);
            }

            if($this->isAvatarChanged()){
                ThumbUtil::deleteThumbByShortPath($this->old_user->path_to_avatar);
            }

            if($this->isPasswordChanged()){
                $password_validation_rule =  array('password', 'compare');
                if(!$this->customValidation($password_validation_rule)) return false;

                $this->password = $this->encrypt($this->password);
            }


            return true;
    }

    /**
     * Creates and saves avatar thumb
     * @param bool $default_thumb use default thumb
     * @return void
     */
    private function appendWithThumb($default_thumb = false){

        $ext = substr($this::DEFAULT_AVATAR, strrpos($this::DEFAULT_AVATAR, '.'));
        $avatar_file_name = md5(time().rand());

        if(!$default_thumb){

            $ext = '.'.$this->avatar->extensionName;
            $avatar_file_name = $avatar_file_name.$ext;

            $temp_file_path = $this::IMAGES_LOCATION.$this::TEMP_FILE_NAME.$ext;
            $this->avatar->saveAs(ThumbUtil::getImagesLocationRoot().$temp_file_path);

            ThumbUtil::createSmallThumb($temp_file_path, $this::IMAGES_LOCATION, $avatar_file_name);
            ThumbUtil::deleteThumbByShortPath(ThumbUtil::IMAGES_LOCATION.$temp_file_path);
        }else{
            $avatar_file_name = $avatar_file_name.$ext;
            $path_to_avatar = ThumbUtil::getImagesLocationRoot().$this::IMAGES_LOCATION.'/'.$avatar_file_name;
            copy(ThumbUtil::getImagesLocationRoot().$this::DEFAULT_AVATAR, $path_to_avatar);
        }

        $this->path_to_avatar = ThumbUtil::IMAGES_LOCATION.$this::IMAGES_LOCATION.'/'.$avatar_file_name;

    }

    /**
     * Check for avatar changing
     * @return bool result of checking
     */
    private function isAvatarChanged(){
        if($this->old_user and ($this->old_user->path_to_avatar != $this->path_to_avatar)) return true;
        return false;
    }

    /**
     * Check for password changing
     * @return bool result of checking
     */
    private function isPasswordChanged(){
        if((!$this->old_user) or ($this->old_user->password != $this->password)) return true;
        return false;
    }

    /**
     * Completes custom scenario validation
     * @return boolean result of validation
     */
    private function customValidation($rule){
        $validator = CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2));
        $validator->validate($this, $rule[0]);

        if($this->hasErrors()) return false;
        return true;
    }

    /**
     * Deletes avatar file
     * @return void
     */
    public function delete(){
        ThumbUtil::deleteThumbByShortPath($this->path_to_avatar);
        parent::delete();
    }


    /**
     * Encrypts an argument
     * @param $string encrypting string
     * @return string the md5 hash sum
     */
    public function encrypt($string){
        return md5($string);
    }


    public function getTypes(){
        return array( array("id"=> $this::ADMIN, "name"=>"Администратор"),
                      array("id"=>$this::CUSTOMER, "name"=>"Сотрудник"),
                      array("id"=> $this::CLIENT, "name"=>"Клиент"),
                    );
    }
}